"use client"

import type React from "react"
import { useState, useCallback, useEffect, useRef } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { ScrollArea } from "@/components/ui/scroll-area"
import { Badge } from "@/components/ui/badge"
import { Textarea } from "@/components/ui/textarea"
import { Switch } from "@/components/ui/switch"
import { useToast } from "@/hooks/use-toast"
import { mockData, type AgentComponent, type AgentEdge } from "@/lib/mock-data"
import {
  Save,
  Play,
  Brain,
  DatabaseIcon,
  MessageSquare,
  Search,
  Calculator,
  FileText,
  Globe,
  Code,
  Trash2,
  GitBranch,
  type LucideIcon,
} from "lucide-react"
import { getNodeIcon } from "@/lib/get-node-icon"

const componentTypeConfigs = [
  { id: "llm", type: "llm", label: "语言模型", iconName: "Brain", category: "核心" },
  { id: "memory", type: "memory", label: "记忆系统", iconName: "DatabaseIcon", category: "核心" },
  { id: "planner", type: "planner", label: "规划器", iconName: "MessageSquare", category: "核心" },
  { id: "search", type: "tool", label: "搜索工具", iconName: "Search", category: "工具" },
  { id: "calculator", type: "tool", label: "计算器", iconName: "Calculator", category: "工具" },
  { id: "document", type: "tool", label: "文档处理", iconName: "FileText", category: "工具" },
  { id: "api", type: "tool", label: "API 调用", iconName: "Globe", category: "工具" },
  { id: "code", type: "tool", label: "代码执行", iconName: "Code", category: "工具" },
]

const iconMap: Record<string, LucideIcon> = {
  Brain,
  DatabaseIcon,
  MessageSquare,
  Search,
  Calculator,
  FileText,
  Globe,
  Code,
}

interface AgentBuilderProps {
  agentId?: string
}

type HandlePosition = "top" | "right" | "bottom" | "left"

interface ConnectionHandle {
  componentId: string
  position: HandlePosition
  x: number
  y: number
}

export function AgentBuilder({ agentId }: AgentBuilderProps) {
  const { toast } = useToast()
  const [agentName, setAgentName] = useState("未命名 Agent")
  const [selectedComponent, setSelectedComponent] = useState<AgentComponent | null>(null)
  const [canvasComponents, setCanvasComponents] = useState<AgentComponent[]>([])
  const [edges, setEdges] = useState<AgentEdge[]>([])
  const [connectingFrom, setConnectingFrom] = useState<ConnectionHandle | null>(null)
  const [tempConnectionEnd, setTempConnectionEnd] = useState<{ x: number; y: number } | null>(null)
  const [hoveredHandle, setHoveredHandle] = useState<ConnectionHandle | null>(null)
  const [draggingComponent, setDraggingComponent] = useState<string | null>(null)
  const [dragOffset, setDragOffset] = useState({ x: 0, y: 0 })
  const canvasRef = useRef<HTMLDivElement>(null)
  const [isLoading, setIsLoading] = useState(true)
  const [mounted, setMounted] = useState(false)

  useEffect(() => {
    setMounted(true)
  }, [])

  useEffect(() => {
    if (!mounted) return

    setIsLoading(true)
    if (agentId) {
      const agent = mockData.getAgent(agentId)
      if (agent) {
        setAgentName(agent.name)
        setCanvasComponents(agent.components || [])
        setEdges(agent.edges || [])
      }
    }
    setIsLoading(false)
  }, [agentId, mounted])

  const handleDragStart = (e: React.DragEvent, config: any) => {
    e.dataTransfer.setData("componentType", config.type)
    e.dataTransfer.setData("componentLabel", config.label)
    e.dataTransfer.setData("iconName", config.iconName)
    e.dataTransfer.effectAllowed = "copy"
  }

  const handleDrop = useCallback(
    (e: React.DragEvent) => {
      e.preventDefault()
      const componentType = e.dataTransfer.getData("componentType")
      const componentLabel = e.dataTransfer.getData("componentLabel")
      const iconName = e.dataTransfer.getData("iconName")

      const rect = e.currentTarget.getBoundingClientRect()
      const x = e.clientX - rect.left
      const y = e.clientY - rect.top

      const newComponent: AgentComponent = {
        id: `${componentType}-${Date.now()}`,
        type: componentType,
        label: componentLabel,
        x,
        y,
        config: { iconName },
      }

      setCanvasComponents([...canvasComponents, newComponent])
      toast({
        title: "组件已添加",
        description: `${componentLabel} 已添加到画布`,
      })
    },
    [canvasComponents, toast],
  )

  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault()
    e.dataTransfer.dropEffect = "copy"
  }

  const handleComponentClick = (componentId: string, e: React.MouseEvent) => {
    e.stopPropagation()

    if (connectingFrom === null) {
      setConnectingFrom(null)
      setSelectedComponent(null)
    } else if (connectingFrom.componentId === componentId) {
      setConnectingFrom(null)
      toast({
        title: "已取消",
        description: "连接已取消",
      })
    } else {
      const newEdge: AgentEdge = {
        id: `edge-${Date.now()}`,
        source: connectingFrom.componentId,
        target: componentId,
      }
      setEdges([...edges, newEdge])
      setConnectingFrom(null)
      toast({
        title: "连接成功",
        description: "组件已连接",
      })
    }
  }

  const handleDeleteComponent = (componentId: string, e: React.MouseEvent) => {
    e.stopPropagation()
    setCanvasComponents(canvasComponents.filter((c) => c.id !== componentId))
    setEdges(edges.filter((e) => e.source !== componentId && e.target !== componentId))
    if (selectedComponent?.id === componentId) {
      setSelectedComponent(null)
    }
    toast({
      title: "组件已删除",
      description: "组件及其连接已从画布中移除",
    })
  }

  const handleSave = () => {
    const agentData = {
      name: agentName,
      components: canvasComponents,
      edges: edges,
    }

    if (agentId) {
      mockData.updateAgent(agentId, agentData)
      toast({
        title: "保存成功",
        description: "Agent 已更新",
      })
    } else {
      mockData.addAgent({
        ...agentData,
        status: "draft",
        lastRun: "从未运行",
        createdAt: new Date().toISOString().split("T")[0],
      })
      toast({
        title: "保存成功",
        description: "新 Agent 已创建",
      })
    }
  }

  const handleTest = () => {
    toast({
      title: "测试运行中",
      description: "Agent 正在执行测试...",
    })
    setTimeout(() => {
      toast({
        title: "测试完成",
        description: "Agent 执行成功",
      })
    }, 2000)
  }

  const handleComponentMouseDown = (componentId: string, e: React.MouseEvent) => {
    if (e.detail === 2) return

    const component = canvasComponents.find((c) => c.id === componentId)
    if (!component) return

    const rect = canvasRef.current?.getBoundingClientRect()
    if (!rect) return

    setDraggingComponent(componentId)
    setDragOffset({
      x: e.clientX - rect.left - component.x,
      y: e.clientY - rect.top - component.y,
    })
    e.stopPropagation()
  }

  const getHandlePosition = (component: AgentComponent, position: HandlePosition): { x: number; y: number } => {
    const nodeWidth = 150
    const nodeHeight = 80

    switch (position) {
      case "top":
        return { x: component.x, y: component.y - nodeHeight / 2 }
      case "right":
        return { x: component.x + nodeWidth / 2, y: component.y }
      case "bottom":
        return { x: component.x, y: component.y + nodeHeight / 2 }
      case "left":
        return { x: component.x - nodeWidth / 2, y: component.y }
    }
  }

  const handleConnectionStart = (componentId: string, position: HandlePosition, e: React.MouseEvent) => {
    e.stopPropagation()
    const component = canvasComponents.find((c) => c.id === componentId)
    if (!component) return

    const handlePos = getHandlePosition(component, position)
    setConnectingFrom({
      componentId,
      position,
      x: handlePos.x,
      y: handlePos.y,
    })
    setTempConnectionEnd(handlePos)
  }

  const handleCanvasMouseMove = useCallback(
    (e: React.MouseEvent) => {
      if (!canvasRef.current) return

      if (connectingFrom) {
        const rect = canvasRef.current.getBoundingClientRect()
        const x = e.clientX - rect.left
        const y = e.clientY - rect.top
        setTempConnectionEnd({ x, y })
      }

      if (draggingComponent) {
        const rect = canvasRef.current.getBoundingClientRect()
        const x = e.clientX - rect.left - dragOffset.x
        const y = e.clientY - rect.top - dragOffset.y

        setCanvasComponents((components) =>
          components.map((comp) =>
            comp.id === draggingComponent
              ? {
                  ...comp,
                  x: Math.max(75, Math.min(rect.width - 75, x)),
                  y: Math.max(40, Math.min(rect.height - 40, y)),
                }
              : comp,
          ),
        )
      }
    },
    [connectingFrom, draggingComponent, dragOffset],
  )

  const handleConnectionEnd = (targetComponentId: string, targetPosition: HandlePosition, e: React.MouseEvent) => {
    e.stopPropagation()

    if (!connectingFrom || connectingFrom.componentId === targetComponentId) {
      setConnectingFrom(null)
      setTempConnectionEnd(null)
      return
    }

    const newEdge: AgentEdge = {
      id: `edge-${Date.now()}`,
      source: connectingFrom.componentId,
      target: targetComponentId,
      sourceHandle: connectingFrom.position,
      targetHandle: targetPosition,
    }

    setEdges([...edges, newEdge])
    setConnectingFrom(null)
    setTempConnectionEnd(null)

    toast({
      title: "连接成功",
      description: "组件已连接",
    })
  }

  const handleCanvasMouseUp = useCallback(() => {
    setDraggingComponent(null)
    setConnectingFrom(null)
    setTempConnectionEnd(null)
  }, [])

  const getComponentIcon = (component: AgentComponent) => {
    return getNodeIcon(component)
  }

  const renderEdges = () => {
    return edges.map((edge) => {
      const sourceComp = canvasComponents.find((c) => c.id === edge.source)
      const targetComp = canvasComponents.find((c) => c.id === edge.target)

      if (!sourceComp || !targetComp) return null

      const sourcePos = getHandlePosition(sourceComp, edge.sourceHandle || "right")
      const targetPos = getHandlePosition(targetComp, edge.targetHandle || "left")

      const x1 = sourcePos.x
      const y1 = sourcePos.y
      const x2 = targetPos.x
      const y2 = targetPos.y

      const dx = x2 - x1
      const dy = y2 - y1
      const distance = Math.sqrt(dx * dx + dy * dy)
      const controlOffset = Math.min(distance * 0.5, 150)

      let controlX1 = x1
      let controlY1 = y1
      let controlX2 = x2
      let controlY2 = y2

      if (edge.sourceHandle === "right") controlX1 = x1 + controlOffset
      else if (edge.sourceHandle === "left") controlX1 = x1 - controlOffset
      else if (edge.sourceHandle === "top") controlY1 = y1 - controlOffset
      else if (edge.sourceHandle === "bottom") controlY1 = y1 + controlOffset

      if (edge.targetHandle === "right") controlX2 = x2 + controlOffset
      else if (edge.targetHandle === "left") controlX2 = x2 - controlOffset
      else if (edge.targetHandle === "top") controlY2 = y2 - controlOffset
      else if (edge.targetHandle === "bottom") controlY2 = y2 + controlOffset

      return (
        <g key={edge.id}>
          <path
            d={`M ${x1} ${y1} C ${controlX1} ${controlY1}, ${controlX2} ${controlY2}, ${x2} ${y2}`}
            stroke="hsl(var(--primary))"
            strokeWidth="2"
            fill="none"
            markerEnd="url(#arrowhead)"
            className="transition-all"
          />
          <circle
            cx={(x1 + x2) / 2}
            cy={(y1 + y2) / 2}
            r="10"
            fill="hsl(var(--background))"
            stroke="hsl(var(--primary))"
            strokeWidth="2"
            cursor="pointer"
            className="hover:fill-destructive hover:stroke-destructive transition-colors"
            onClick={(e) => {
              e.stopPropagation()
              setEdges(edges.filter((e) => e.id !== edge.id))
              toast({
                title: "连接已删除",
                description: "组件连接已移除",
              })
            }}
          />
          <text
            x={(x1 + x2) / 2}
            y={(y1 + y2) / 2}
            textAnchor="middle"
            dominantBaseline="middle"
            fontSize="12"
            fontWeight="bold"
            fill="hsl(var(--primary))"
            pointerEvents="none"
            className="select-none"
          >
            ×
          </text>
        </g>
      )
    })
  }

  const renderTempConnection = () => {
    if (!connectingFrom || !tempConnectionEnd) return null

    const x1 = connectingFrom.x
    const y1 = connectingFrom.y
    const x2 = tempConnectionEnd.x
    const y2 = tempConnectionEnd.y

    const dx = x2 - x1
    const dy = y2 - y1
    const distance = Math.sqrt(dx * dx + dy * dy)
    const controlOffset = Math.min(distance * 0.5, 150)

    let controlX1 = x1
    let controlY1 = y1

    if (connectingFrom.position === "right") controlX1 = x1 + controlOffset
    else if (connectingFrom.position === "left") controlX1 = x1 - controlOffset
    else if (connectingFrom.position === "top") controlY1 = y1 - controlOffset
    else if (connectingFrom.position === "bottom") controlY1 = y1 + controlOffset

    return (
      <path
        d={`M ${x1} ${y1} C ${controlX1} ${controlY1}, ${x2} ${y2}, ${x2} ${y2}`}
        stroke="hsl(var(--primary))"
        strokeWidth="2"
        strokeDasharray="5,5"
        fill="none"
        className="transition-all opacity-60"
      />
    )
  }

  const renderConnectionHandles = (component: AgentComponent) => {
    const positions: HandlePosition[] = ["top", "right", "bottom", "left"]

    return positions.map((position) => {
      let style: React.CSSProperties = {
        position: "absolute",
        width: "12px",
        height: "12px",
        borderRadius: "50%",
        border: "2px solid hsl(var(--primary))",
        background: "hsl(var(--background))",
        cursor: "crosshair",
        zIndex: 10,
        opacity: 0,
        transition: "opacity 0.2s",
      }

      switch (position) {
        case "top":
          style = { ...style, top: "-6px", left: "50%", transform: "translateX(-50%)" }
          break
        case "right":
          style = { ...style, right: "-6px", top: "50%", transform: "translateY(-50%)" }
          break
        case "bottom":
          style = { ...style, bottom: "-6px", left: "50%", transform: "translateX(-50%)" }
          break
        case "left":
          style = { ...style, left: "-6px", top: "50%", transform: "translateY(-50%)" }
          break
      }

      const isHovered = hoveredHandle?.componentId === component.id && hoveredHandle?.position === position

      return (
        <div
          key={position}
          style={{
            ...style,
            opacity: isHovered || connectingFrom ? 1 : undefined,
          }}
          className="group-hover:opacity-100"
          onMouseDown={(e) => handleConnectionStart(component.id, position, e)}
          onMouseUp={(e) => handleConnectionEnd(component.id, position, e)}
          onMouseEnter={() => {
            const handlePos = getHandlePosition(component, position)
            setHoveredHandle({ componentId: component.id, position, ...handlePos })
          }}
          onMouseLeave={() => setHoveredHandle(null)}
        />
      )
    })
  }

  if (!mounted || isLoading) {
    return (
      <div className="h-[calc(100vh-8rem)] flex items-center justify-center">
        <div className="text-center space-y-2">
          <div className="h-8 w-8 border-4 border-primary border-t-transparent rounded-full animate-spin mx-auto" />
          <p className="text-sm text-muted-foreground">加载中...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="h-[calc(100vh-8rem)] flex flex-col gap-4">
      {/* Toolbar */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-4">
          <Input value={agentName} onChange={(e) => setAgentName(e.target.value)} className="w-64 font-semibold" />
          <Badge variant="outline" className="gap-1">
            <Brain className="h-3 w-3" />
            LangGraph Agent
          </Badge>
        </div>
        <div className="flex items-center gap-2">
          <Button variant="outline" onClick={handleTest}>
            <Play className="mr-2 h-4 w-4" />
            测试
          </Button>
          <Button onClick={handleSave}>
            <Save className="mr-2 h-4 w-4" />
            保存
          </Button>
        </div>
      </div>

      {/* Main Content */}
      <div className="flex-1 grid grid-cols-[280px_1fr_320px] gap-4 min-h-0">
        {/* Component Library */}
        <Card className="flex flex-col">
          <CardHeader className="pb-3">
            <CardTitle className="text-base">组件库</CardTitle>
            <CardDescription>拖拽组件到画布</CardDescription>
          </CardHeader>
          <CardContent className="flex-1 p-0">
            <ScrollArea className="h-full px-4 pb-4">
              <div className="space-y-4">
                {["核心", "工具"].map((category) => (
                  <div key={category} className="space-y-2">
                    <h4 className="text-sm font-medium text-muted-foreground">{category}</h4>
                    <div className="space-y-1">
                      {componentTypeConfigs
                        .filter((config) => config.category === category)
                        .map((config) => {
                          const IconComponent = iconMap[config.iconName]
                          return (
                            <div
                              key={config.id}
                              draggable
                              onDragStart={(e) => handleDragStart(e, config)}
                              className="flex items-center gap-3 p-3 rounded-lg border bg-card hover:bg-accent cursor-move transition-colors"
                            >
                              <div className="h-8 w-8 rounded-md bg-primary/10 flex items-center justify-center flex-shrink-0">
                                <IconComponent className="h-4 w-4 text-primary" />
                              </div>
                              <span className="text-sm font-medium">{config.label}</span>
                            </div>
                          )
                        })}
                    </div>
                  </div>
                ))}
              </div>
            </ScrollArea>
          </CardContent>
        </Card>

        {/* Canvas */}
        <Card className="relative overflow-hidden">
          <div
            ref={canvasRef}
            onDrop={handleDrop}
            onDragOver={handleDragOver}
            onMouseMove={handleCanvasMouseMove}
            onMouseUp={handleCanvasMouseUp}
            onMouseLeave={handleCanvasMouseUp}
            onClick={() => {
              setSelectedComponent(null)
            }}
            className="absolute inset-0 bg-[radial-gradient(#e5e7eb_1px,transparent_1px)] [background-size:16px_16px] dark:bg-[radial-gradient(#27272a_1px,transparent_1px)]"
          >
            <svg className="absolute inset-0 w-full h-full pointer-events-none" style={{ zIndex: 1 }}>
              <defs>
                <marker id="arrowhead" markerWidth="10" markerHeight="10" refX="9" refY="3" orient="auto">
                  <polygon points="0 0, 10 3, 0 6" fill="hsl(var(--primary))" />
                </marker>
              </defs>
              <g style={{ pointerEvents: "all" }}>
                {renderEdges()}
                {renderTempConnection()}
              </g>
            </svg>

            {canvasComponents.length === 0 ? (
              <div className="absolute inset-0 flex items-center justify-center" style={{ zIndex: 2 }}>
                <div className="text-center space-y-2">
                  <Brain className="h-12 w-12 text-muted-foreground mx-auto mb-4" />
                  <p className="text-muted-foreground">从左侧拖拽组件到此处开始构建 Agent</p>
                  <Badge variant="outline">拖动组件调整位置 • 从连接点拖拽创建连线</Badge>
                </div>
              </div>
            ) : (
              <div style={{ position: "relative", zIndex: 2 }}>
                {canvasComponents.map((comp) => {
                  const IconComponent = getComponentIcon(comp)
                  const isSelected = selectedComponent?.id === comp.id
                  const isDragging = draggingComponent === comp.id

                  return (
                    <div
                      key={comp.id}
                      style={{
                        position: "absolute",
                        left: comp.x - 75,
                        top: comp.y - 40,
                        cursor: isDragging ? "grabbing" : "grab",
                      }}
                      onClick={(e) => {
                        e.stopPropagation()
                        setSelectedComponent(comp)
                      }}
                      onMouseDown={(e) => handleComponentMouseDown(comp.id, e)}
                      className={`w-[150px] p-3 rounded-lg border-2 bg-card hover:border-primary transition-all shadow-sm group ${
                        isSelected ? "border-primary ring-2 ring-primary/20" : ""
                      } ${isDragging ? "shadow-lg scale-105" : ""}`}
                    >
                      {renderConnectionHandles(comp)}

                      <div className="flex items-center gap-2">
                        <div className="h-8 w-8 rounded-md bg-primary/10 flex items-center justify-center flex-shrink-0">
                          <IconComponent className="h-4 w-4 text-primary" />
                        </div>
                        <span className="text-sm font-medium truncate flex-1">{comp.label}</span>
                        <Button
                          variant="ghost"
                          size="icon"
                          className="h-6 w-6 opacity-0 group-hover:opacity-100 transition-opacity"
                          onClick={(e) => handleDeleteComponent(comp.id, e)}
                          onMouseDown={(e) => e.stopPropagation()}
                        >
                          <Trash2 className="h-3 w-3" />
                        </Button>
                      </div>
                    </div>
                  )
                })}
              </div>
            )}
          </div>
        </Card>

        {/* Properties Panel */}
        <Card className="flex flex-col">
          <CardHeader className="pb-3">
            <CardTitle className="text-base">组件配置</CardTitle>
            <CardDescription>{connectingFrom ? "拖拽到目标连接点" : "配置选中组件"}</CardDescription>
          </CardHeader>
          <CardContent className="flex-1">
            {connectingFrom ? (
              <div className="flex flex-col items-center justify-center h-full gap-4">
                <div className="h-16 w-16 rounded-full bg-primary/10 flex items-center justify-center animate-pulse">
                  <GitBranch className="h-8 w-8 text-primary" />
                </div>
                <div className="text-center space-y-2">
                  <p className="font-medium">连接模式</p>
                  <p className="text-sm text-muted-foreground">拖拽到目标组件的连接点</p>
                </div>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => {
                    setConnectingFrom(null)
                    setTempConnectionEnd(null)
                    toast({
                      title: "已取消",
                      description: "连接已取消",
                    })
                  }}
                >
                  取消连接
                </Button>
              </div>
            ) : selectedComponent ? (
              <ScrollArea className="h-full">
                <div className="space-y-4">
                  <div className="space-y-2">
                    <Label>组件名称</Label>
                    <Input
                      value={selectedComponent.label}
                      onChange={(e) => {
                        const updated = canvasComponents.map((c) =>
                          c.id === selectedComponent.id ? { ...c, label: e.target.value } : c,
                        )
                        setCanvasComponents(updated)
                        setSelectedComponent({ ...selectedComponent, label: e.target.value })
                      }}
                    />
                  </div>
                  <div className="space-y-2">
                    <Label>组件类型</Label>
                    <Input value={selectedComponent.type} disabled />
                  </div>

                  {selectedComponent.type === "llm" && (
                    <>
                      <div className="space-y-2">
                        <Label>模型选择</Label>
                        <Input placeholder="gpt-4" />
                      </div>
                      <div className="space-y-2">
                        <Label>系统提示词</Label>
                        <Textarea placeholder="你是一个有帮助的 AI 助手..." className="min-h-[100px] resize-none" />
                      </div>
                      <div className="space-y-2">
                        <Label>温度</Label>
                        <Input type="number" placeholder="0.7" step="0.1" min="0" max="2" />
                      </div>
                    </>
                  )}

                  {selectedComponent.type === "memory" && (
                    <>
                      <div className="space-y-2">
                        <Label>记忆类型</Label>
                        <Input placeholder="对话历史" />
                      </div>
                      <div className="flex items-center justify-between">
                        <Label>启用长期记忆</Label>
                        <Switch />
                      </div>
                      <div className="space-y-2">
                        <Label>最大记忆条数</Label>
                        <Input type="number" placeholder="100" />
                      </div>
                    </>
                  )}

                  {selectedComponent.type === "tool" && (
                    <>
                      <div className="space-y-2">
                        <Label>工具描述</Label>
                        <Textarea placeholder="描述这个工具的功能..." className="min-h-[80px] resize-none" />
                      </div>
                      <div className="space-y-2">
                        <Label>参数配置</Label>
                        <Input placeholder='{"param1": "value1"}' />
                      </div>
                      <div className="flex items-center justify-between">
                        <Label>需要确认</Label>
                        <Switch />
                      </div>
                    </>
                  )}

                  <div className="pt-4 border-t">
                    <Button
                      variant="outline"
                      size="sm"
                      className="w-full bg-transparent"
                      onClick={(e) => {
                        e.stopPropagation()
                        handleComponentClick(selectedComponent.id, e)
                      }}
                    >
                      <GitBranch className="mr-2 h-4 w-4" />
                      连接到其他组件
                    </Button>
                  </div>
                </div>
              </ScrollArea>
            ) : (
              <div className="flex items-center justify-center h-full text-sm text-muted-foreground text-center px-4">
                <div className="space-y-2">
                  <p>选择一个组件查看配置</p>
                  <p className="text-xs">从组件边缘的连接点拖拽创建连线</p>
                </div>
              </div>
            )}
          </CardContent>
        </Card>
      </div>
    </div>
  )
}
